{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7373356a",
   "metadata": {},
   "source": [
    "# 回文判断"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a5444d7e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "// 两边向中间扫描\n",
    "#include <iostream>\n",
    "bool IsPailndrome(const char* s, int n){\n",
    "    // 非法输入\n",
    "    if(s == NULL || n < 1){\n",
    "        return false;\n",
    "    }\n",
    "    const char* front, *back;\n",
    "    // 初始化头指针/尾指针\n",
    "    front = s;\n",
    "    back = s + n - 1;\n",
    "    while(front < back){\n",
    "        if(*front != *back){\n",
    "            return false;\n",
    "        }\n",
    "        ++front;\n",
    "        --back;\n",
    "    }\n",
    "    return true;\n",
    "}\n",
    "\n",
    "const char* n = \"12321\";\n",
    "const char* s = \"abcba\";\n",
    "const char* ss = \"ehegergrsazwgr\";\n",
    "const char* nn = \"1221\";\n",
    "std::cout <<(IsPailndrome(n,5)?\"True\":\"False\")<< std::endl;\n",
    "std::cout <<(IsPailndrome(nn,4)?\"True\":\"False\")<< std::endl;\n",
    "std::cout <<(IsPailndrome(s,5)?\"True\":\"False\")<< std::endl;\n",
    "std::cout <<(IsPailndrome(ss,5)?\"True\":\"False\")<< std::endl;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d3472385",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "//中间向两端扫描\n",
    "#include <iostream>\n",
    "bool IsPailndrome(const char *s, int n){\n",
    "    if(s == NULL || n < 1){\n",
    "        return false;\n",
    "    }\n",
    "    const char* left, *right;\n",
    "    // m定位到中间位置\n",
    "    int m = ((n >> 1) - 1) >= 0 ? (n >> 1) - 1 : 0;\n",
    "    left = s + m;\n",
    "    right = s + n - 1 - m;\n",
    "    //std::cout <<s<<\" left: \"<<m<<\" right : \"<<n-1-m<< std::endl;\n",
    "    while(left >= s){\n",
    "        if(*left != *right){\n",
    "            return false;\n",
    "        }\n",
    "        --left;\n",
    "        ++right;\n",
    "    }\n",
    "    return true;\n",
    "}\n",
    "\n",
    "const char* n = \"12321\";\n",
    "const char* s = \"abcba\";\n",
    "const char* ss = \"ehegergrsazwgr\";\n",
    "const char* nn = \"1221\";\n",
    "std::cout <<(IsPailndrome(n,5)?\"True\":\"False\")<< std::endl;\n",
    "std::cout <<(IsPailndrome(nn,4)?\"True\":\"False\")<< std::endl;\n",
    "std::cout <<(IsPailndrome(s,5)?\"True\":\"False\")<< std::endl;\n",
    "std::cout <<(IsPailndrome(ss,5)?\"True\":\"False\")<< std::endl;"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++14",
   "language": "C++14",
   "name": "xcpp14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
